<?php

namespace App\Http\Controllers\Common;

use App\Http\Controllers\Controller;
use App\Models\Attachment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class AttachmentController extends Controller
{
    public function list()
    {
        $disk = Storage::disk("oss");
        $id = request()->get('attachable_id');
        $type = request()->get('attachable_type');
        $result = Attachment::whereAttachableId($id)->whereAttachableType($type)->get();
        $result->each(function (Attachment $attachment) use ($disk) {
            $attachment->setAppends(["downloadUrl", "previewUrl"]);
        });
        $ossEndPoint = config('filesystems.disks.oss.endpoint');
        if (!Str::startsWith($ossEndPoint, "http")) {
            $ossEndPoint = "https://" . $ossEndPoint;
        }
        return response()->json(compact(['result', 'ossEndPoint']));
    }

    public function delete($id)
    {
        Attachment::where('id', $id)->delete();
        $result = 'ok';
        return response()->json(compact(['result']));
    }
}
